<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Perdesaan_model extends MY_Model {

    function __construct() {
        parent::__construct("perdesaan", "code", Array(
            "kecamatan_code" => "Kecamatan_model"
        ));
    }

    public function findByName($name, $fetchForeign = false, $depth = 1) {
        $where = "UCASE(REPLACE(display_name, ' ', '')) LIKE UCASE(REPLACE('" . $name . "', ' ', ''))";
        $result = $this->read($where, $fetchForeign, $depth);
        $resObj = NULL;
        if (count($result) > 0) {
            $resObj = $result[0];
        }
        return $resObj;
    }

    protected function read($where = Array(), $fetchForeign = false, $depth = 1, $page = -1, $limit = 10) {
        $results = parent::read($where, $fetchForeign, $depth, $page, $limit);

        foreach ($results as $result) {
            $kecObj = $result->kecamatan_code;
            if (is_string($kecObj)) {
                $this->load->model("Kecamatan_model");
                $kecObj = $this->Kecamatan_model->findById($kecObj);
            }
            if (($result->latitude == null || $result->longlatitude == null) && ($kecObj != null)) {
                $result->latitude = $kecObj->latitude;
                $result->longlatitude = $kecObj->longlatitude;
            }
        }

        return $results;
    }

}